// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
}) // 使用当前云环境

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  const {
    _id
  } = event
  const useNum = Number(event.useNum)
  const orderRes = await db.collection('orders')
    .where({
      _id
    })
    .get()

  const order = orderRes.data[0]
  if (!order) return "order doesn't exist"

  // 更新水票使用数量
  const nowTime = new Date().getTime()
  const ticketInfo = order.ticketInfo
  const used = Number(ticketInfo.used || 0),
    totalAmount = Number(ticketInfo.totalAmount || 0)
  ticketInfo.used = (used + useNum)
  if (ticketInfo.used < 0 || ticketInfo.used > totalAmount) return "error ticket amount"

  await db.collection('orders')
    .where({
      _id
    })
    .update({
      data: {
        ticketInfo,
        updateTime: nowTime
      }
    })

  // 增加订单
  if (useNum > 0) {
    const ticketOrderId = order._id
    order._id = undefined
    order.ticketInfo = undefined
    order.ticketOrderId = ticketOrderId
    order.createTime = nowTime
    order.updateTime = nowTime
    order.goodsList[0].num = useNum
    order.status = '待配送'
    order.stepFee = order.stepFee / (ticketInfo.totalAmount - ticketInfo.gift) * useNum
    const newOrder = await db.collection('orders')
      .add({
        data: order
      })
    await notifyDeliveryMen(newOrder._id)

    return newOrder
  }

  return 'success'
}

async function notifyDeliveryMen(orderId) {
  return await cloud.callFunction({
    name: 'notifyDelivery',
    data: {
      orderId
    }
  })
}